#include "./../inc/main.h"

int main()
{
    Lcd *lcd = Lcd::instance();
    Touch *touch = Touch::instance();
    MainPage mainPage;
    MatchPage matchPage; // 匹配页面实例
    GameMode currentMode = None;

    // 定义返回按钮的统一位置和尺寸
    const int RETURN_BTN_X = LCD_WIDTH - 110; // 距离右边缘100px
    const int RETURN_BTN_Y = LCD_HEIGHT - 70; // 距离下边缘70px
    const int RETURN_BTN_WIDTH = 100;
    const int RETURN_BTN_HEIGHT = 60;

    while (true)
    {
        // 显示主页面并等待选择模式
        mainPage.display(lcd);
        currentMode = mainPage.handleTouch(touch, lcd);

        if (currentMode == None)
            continue;

        // 网络对战模式
        if (currentMode == NetworkGame)
        {
            // 连接服务器
            if (connect_to_server() != 0)
            {
                continue;
            }

            // 发送匹配请求并显示匹配页面
            send_match_request();
            matchPage.display(lcd);

            // 等待匹配结果或取消操作
            bool is_cancelled = false;
            while (get_match_state() == MATCH_SEARCHING)
            {
                // 检查是否点击取消按钮
                if (matchPage.check_cancel_click(touch))
                {
                    cout << "取消匹配" << endl;
                    send_cancel_match(); // 通知服务器取消匹配
                    is_cancelled = true;
                    break; // 跳出匹配等待循环
                }
                matchPage.display(lcd);
                usleep(50000); // 减少刷新间隔以提高响应性
            }
            // 处理匹配结果
            if (is_cancelled || get_match_state() != MATCH_SUCCESS)
            {
                disconnect_from_server();
                reset_match_state();
                continue;
            }
            // 匹配成功，进入游戏
            ChessGame game(currentMode);
            game.initBoard();
            while (!game.isGameOver())
            {
                game.displayBoard(lcd);
                // 绘制返回按钮
                MatchPage::drawReturnButton(lcd, RETURN_BTN_X, RETURN_BTN_Y, RETURN_BTN_WIDTH, RETURN_BTN_HEIGHT);
                lcd->swapBuffers();

                if(hasOpponentMove)
                {
                    game.handleNetworkMove(opponentMove.fromX, opponentMove.fromY, opponentMove.toX, opponentMove.toY);
                    hasOpponentMove = false;
                    continue;
                }

                Point touchPoint;
                touch->wait(touchPoint);
                if (MatchPage::checkReturnButtonClick(touch, RETURN_BTN_X, RETURN_BTN_Y, RETURN_BTN_WIDTH, RETURN_BTN_HEIGHT))
                {
                    // 返回主菜单
                    cout << "返回主菜单" << endl;
                    disconnect_from_server();
                    reset_match_state();
                    break;
                }
                game.handleTouch(touchPoint, lcd);
                usleep(10000);
            }
            if (!game.isGameOver())
                continue; // 如果是返回主菜单，则跳过游戏结束处理

            game.showMessage(lcd, "游戏结束");
            usleep(2000000);
            // 游戏结束，断开连接
            disconnect_from_server();
            reset_match_state();
        }
        // 人机模式

        else if (currentMode == AiGame)
        {
            ChessGame game(currentMode);
            game.initBoard();

            // 显示难度选择界面
            int *buffer = lcd->getBuffer();
            memset(buffer, 0xFFFFF0, LCD_WIDTH * LCD_HEIGHT * sizeof(int));
            ShowFont::instance()->display("选择难度", 32, 200, 50, 0xFFFFF0, 0x000000, 300, 150);

            // 绘制难度按钮
            Button easyBtn = {200, 250, 150, 60, "简单", 0x8B4513, 0xFFFFFF};
            Button hardBtn = {450, 250, 150, 60, "困难", 0x8B4513, 0xFFFFFF};
            // 绘制返回按钮
            MatchPage::drawReturnButton(lcd, RETURN_BTN_X, RETURN_BTN_Y, RETURN_BTN_WIDTH, RETURN_BTN_HEIGHT);

            bool difficultySelected = false;
            bool returnToMain = false;

            while (!difficultySelected && !returnToMain)
            {
                // 每次循环都重新绘制界面
                memset(buffer, 0xFFFFF0, LCD_WIDTH * LCD_HEIGHT * sizeof(int));
                ShowFont::instance()->display("选择难度", 32, 200, 50, 0xFFFFF0, 0x000000, 300, 150);

                // 绘制难度按钮
                BMP::drawRoundRectangle(buffer, easyBtn.x, easyBtn.y, easyBtn.x + easyBtn.width, easyBtn.y + easyBtn.height, easyBtn.bgColor, 10, 0x000000, 2);
                BMP::drawRoundRectangle(buffer, hardBtn.x, hardBtn.y, hardBtn.x + hardBtn.width, hardBtn.y + hardBtn.height, hardBtn.bgColor, 10, 0x000000, 2);
                ShowFont::instance()->display(easyBtn.text.c_str(), 24, easyBtn.width, easyBtn.height, easyBtn.bgColor, easyBtn.textColor, easyBtn.x + 10, easyBtn.y + 10);
                ShowFont::instance()->display(hardBtn.text.c_str(), 24, hardBtn.width, hardBtn.height, hardBtn.bgColor, hardBtn.textColor, hardBtn.x + 10, hardBtn.y + 10);

                // 绘制返回按钮
                MatchPage::drawReturnButton(lcd, RETURN_BTN_X, RETURN_BTN_Y, RETURN_BTN_WIDTH, RETURN_BTN_HEIGHT);
                lcd->swapBuffers();

                // 等待用户选择难度
                Point touchPoint;
                touch->wait(touchPoint);
                if (touchPoint.x() >= easyBtn.x && touchPoint.x() <= easyBtn.x + easyBtn.width &&
                    touchPoint.y() >= easyBtn.y && touchPoint.y() <= easyBtn.y + easyBtn.height)
                {
                    game.setAIStrategy(new EasyAIStrategy());
                    difficultySelected = true;
                }
                else if (touchPoint.x() >= hardBtn.x && touchPoint.x() <= hardBtn.x + hardBtn.width &&
                         touchPoint.y() >= hardBtn.y && touchPoint.y() <= hardBtn.y + hardBtn.height)
                {
                    game.setAIStrategy(new HardAIStrategy());
                    difficultySelected = true;
                }
                else if (MatchPage::checkReturnButtonClick(touch, RETURN_BTN_X, RETURN_BTN_Y, RETURN_BTN_WIDTH, RETURN_BTN_HEIGHT))
                {
                    // 返回主菜单
                    returnToMain = true;
                }
            }

            // 如果选择返回主菜单，则跳出当前模式循环
            if (returnToMain)
            {
                continue;
            }
            // 开始游戏循环
            while (!game.isGameOver())
            {
                game.displayBoard(lcd);
                // 绘制返回按钮
                MatchPage::drawReturnButton(lcd, RETURN_BTN_X, RETURN_BTN_Y, RETURN_BTN_WIDTH, RETURN_BTN_HEIGHT);
                lcd->swapBuffers();

                if (game.getCurrentPlayer() == Red)
                {
                    // 玩家回合
                    Point touchPoint;
                    touch->wait(touchPoint);
                    if (MatchPage::checkReturnButtonClick(touch, RETURN_BTN_X, RETURN_BTN_Y, RETURN_BTN_WIDTH, RETURN_BTN_HEIGHT))
                    {
                        // 返回主菜单
                        break;
                    }
                    game.handleTouch(touchPoint, lcd);
                }
                else
                {
                    // AI回合
                    game.makeAIMove();
                }
            }
            if (!game.isGameOver())
                continue;

            game.showMessage(lcd, "游戏结束！");
            usleep(2000000);
        }
        else // 单人模式
        {
            ChessGame game(currentMode);
            game.initBoard();
            while (!game.isGameOver())
            {
                game.displayBoard(lcd);
                // 绘制返回按钮 (右下角)
                MatchPage::drawReturnButton(lcd, RETURN_BTN_X, RETURN_BTN_Y, RETURN_BTN_WIDTH, RETURN_BTN_HEIGHT);
                lcd->swapBuffers();
                Point touchPoint;
                touch->wait(touchPoint);
                if (MatchPage::checkReturnButtonClick(touch, RETURN_BTN_X, RETURN_BTN_Y, RETURN_BTN_WIDTH, RETURN_BTN_HEIGHT))
                {
                    break;
                }
                game.handleTouch(touchPoint, lcd);
                usleep(100000); // 100ms
            }
            game.showMessage(lcd, "游戏结束！");
            usleep(2000000);
        }
    }

    // 释放资源
    Touch::del_instance();
    Lcd::delInstance();
    return 0;
}

